// pages/clazzDetials/clazzDetails.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id:null,
    title:'',
    images:'',
    summary:'',
    consultantId:null,
    isCollected: false,// 初始状态为未收藏
    showDialog:false,
    evaluationContent:'',
    rating:0,//评级
    name:'',
    videoSrc: '', // 视频源地址
    // posterSrc: '', // 封面图地址
    courses: [
      { name: '第一章名字', duration: 24,isBuy:0 },
      { name: '第二章名字', duration: 25,isBuy:0},
      { name: '第三章名字', duration: 38,isBuy:0 },
      { name: '第四章名字', duration: 31,isBuy:0 },
      { name: '第五章名字', duration: 27,isBuy:0 }
    ],
    evaluations: [
      {
        username: '',
        rating:null,
        comment: '',
        time: ''
      },
    ],
    consultant:{
      name:'',
      avatar:'',
      address:'',
      field:'',
      levelId:'',
      certify:''
    },
    showCourse:[],
    showEvaluations: [],
    showAll: false,
    tabIndex: 3,
    sortOptions: ['最新发表', '最后回复', '回复数量'],
    sortIndex: 0,
    showPauseButton: true, // 是否显示暂停按钮
    comments: [
      {
        id: 1,
        content: '第一个交流的【题目】是这个',
        user: '用户9527',
        time: '15分钟前',
        showReplies: false,
      
        replies: [
          { id: 1, content: '回复1' },
          { id: 2, content: '回复2' },
          // 更多回复...
        ]
      },
      {
        id: 2,
        content: '第二个主题的【题目】是这个',
        user: '用户9527',
        time: '30分钟前',
        showReplies: false,
        replies: [
          { id: 1, content: '回复1' },
          { id: 2, content: '回复2' },
          // 更多回复...
        ]
      },
      // 更多评论...
    ],
    // exchanges: [
    //   {
    //     title: '第一个交流的【题目】是这个',
    //     username: '用户9527',
    //     time: '15分钟前',
    //     replies: 12
    //   },
    //   {
    //     title: '第二个主题的【题目】是这个',
    //     username: '用户9527',
    //     time: '30分钟前',
    //     replies: 204
    //   },
    //   {
    //     title: '第三个主题的【题目】是这个',
    //     username: '用户9527',
    //     time: '昨天',
    //     replies: 12
    //   },
    //   {
    //     title: '第四个主题的【题目】是这个',
    //     username: '用户9527',
    //     time: '05-14',
    //     replies: 12
    //   },
    //   {
    //     title: '第五个主题的【题目】是这个',
    //     username: '用户9527',
    //     time: '2018-12-23',
    //     replies: 1080
    //   }
    // ],
  },
  buyAllCourses: function () {
    const updatedCourses = this.data.courses.map(course => ({
      ...course,
      isBuy: 1
    }));
    this.setData({ courses: updatedCourses });
    const allCoursesBought = updatedCourses.every(course => course.isBuy === 1);
    if(allCoursesBought){
       wx.showToast({
      title: '购买成功',
      icon:'success',
      duration:6000,
    })}else{
      wx.showToast({
        title: '购买失败',
      })
    }
    
  },
    // 点击切换收藏状态
    toggleCollect() {
        this.setData({
          isCollected: !this.data.isCollected // 取反实现切换
        });
      },
  switchSort(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({ sortIndex: index });
  },

  viewReplies(e) {
    // 处理查看回复的逻辑
    console.log('查看回复');
  },

  viewAll() {
    // 处理查看全部的逻辑
    this.setData({
      showEvaluations: this.data.courses,
      showAll: true
    });
  },
  toggleReply: function (e) {
    const id = e.currentTarget.dataset.id;
    const comments = this.data.comments;
    comments.forEach(comment => {
      if (comment.id === id) {
        comment.showReplies = !comment.showReplies;
      }
    });
    this.setData({ comments });
  },
  AllComment(){
    const comments = this.data.comments.map(comment => {
      return { ...comment, showReplies: true };
    });
    this.setData({ comments });
  },
  addEvaluation(){
    this.setData({
      showDialog:true
    })
  },
  // 评价内容变化
  onContentChange(event) {
    this.setData({
      evaluationContent: event.detail
    });
  },

  // 评级变化
  onRatingChange(event) {
    this.setData({
      rating: event.detail
    });
  },
    // 确认评价
    onConfirm() {
      const { evaluationContent, rating } = this.data;
      if (!evaluationContent || rating === 0) {
        wx.showToast({
          title: '请填写完整评价',
          icon: 'none'
        });
        return;
      }
      // 获取当前日期
      const date = new Date().toISOString().split('T')[0];
      console.log(date);
      wx.request({
        url: 'http://localhost:8080/courseComment',
        method:'POST',
        data:{
          comment:evaluationContent,
          ratting:rating,
          userId:1,
          courseId:1,
          time:date
        },
        success:(res)=>{
          if(res.data.code){
              wx.showToast({
                title: '评价成功',
                icon: 'success'
              });
            // 关闭弹出层
            this.setData({
              showDialog: false,
              evaluationContent: '',
              rating: 0
            });
          }else{
            wx.showToast({
              title: '提交失败，请重试',
              icon: 'none'
            });
          }
        },
        fail:(err)=>{
          console.error('请求失败:', err);
          wx.showToast({
            title: '网络错误，请重试',
            icon: 'none'
          });
        }
      })
    },
  
    // 取消评价
    onCancel() {
      this.setData({
        showDialog: false,
        evaluationContent: '',
        rating: 0
      });
    },
  

  onClickLeft() {
    wx.navigateBack()
  },
  // 视频播放事件
  onPlay: function (event) {
    console.log('视频开始播放');
    this.setData({ showPauseButton: false });
  }, 
  // 视频暂停事件
  onPause: function (event) {
    console.log('视频暂停播放');
    this.setData({ showPauseButton: true });
  },
  //视频播放结束
  onEnded: function (event) {
    console.log('视频播放结束');
  },
  togglePlay: function () {
    const videoContext = wx.createVideoContext('courseVideo');
    if (this.data.showPauseButton) {
      // 当前为暂停状态，点击后继续播放
      videoContext.play();
    } else {
      // 当前为播放状态，点击后暂停
      videoContext.pause();
    }
  },
  startStudy(e) {
    // 处理立即学习的逻辑
    console.log('开始学习');
  },

 
  viewCertificate() {
    // 查看证书的逻辑
    console.log('查看证书');
  },

  viewDetails() {
    const consultantId = this.data.consultantId;
    console.log(consultantId);
    wx.request({
        url: `http://localhost:8080/consultant/searchById?id=${consultantId}`,
        method: "GET",
        header: {
            "Content-Type": "application/json",
        },
        success: (res) => {
            console.log(res.data.data);
            const { name, avatar, address } = res.data.data;
            wx.navigateTo({
                url: '/pages/teacher_hdx/teacher_hdx',
                success: (res) => {
                    const eventChannel = res.eventChannel;
                    eventChannel.emit('sendData', {
                        teacherName: name,
                        teacherAvatar: avatar,
                        teacherAddress: address
                    });
                }
            });
        }
    });
},
  makeAppointment() {
    // 咨询预约的逻辑
    console.log('咨询预约');
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      id: decodeURIComponent(options.id),
      title: decodeURIComponent(options.title),
      images: decodeURIComponent(options.images),
      summary: decodeURIComponent(options.summary),
      videoSrc:decodeURIComponent(options.videoUrl),
      benefits:decodeURIComponent(options.benefits),
      notice:decodeURIComponent(options.notice),
      suitableFor:decodeURIComponent(options.suitableFor),
      prePrice:decodeURIComponent(options.prePrice),
      currentPrice:decodeURIComponent(options.currentPrice),
      consultantId:decodeURIComponent(options.consultantId),
    });
     console.log(this.data);
    const name = decodeURIComponent(options.name || '');
    this.setData({ name }); // 更新标题数据
     this.setData({
      videoSrc: '/videos/video1.mp4', // 替换为实际的视频地址
      posterSrc: '/images/@2x_class.png', // 替换为实际的封面图地址
      showEvaluations: this.data.courses.slice(0, 3),
      showCourse:this.data.evaluations.slice(0,3)
    });
    const consultantId=this.data.consultantId;
    wx.request({
     url: `http://localhost:8080/consultant?id=${consultantId}`,
     method: "GET",
     header: {
       "Content-Type":"application/json"
      },
     success: (res)=>{
      console.log(res.data);
      this.setData({
        consultant:res.data.data
      })
     console.log(this.data.consultant);
     },
     fail: (err)=>{
       console.log("请求失败");
     },
   });
   const id=this.data.id
   wx.request({
     url:  `http://localhost:8080/courseComment/getCommentByCourseId?courseId=${id}`,
     method: "GET",
     header:{
       "Content-Type":"application/json"
     },
     success: (res)=>{
       console.log(res.data.data);
       this.setData({
          evaluations:res.data.data
       })
     }
   })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})